package com.xhlj.aop;
import com.xhlj.annotation.SystemLog;
import com.xhlj.entity.SysLog;
import com.xhlj.mapper.SysLogMapper;
import com.xhlj.service.SysLogService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import java.lang.reflect.Method;
import java.util.Date;

@Aspect
@Component
@EnableAspectJAutoProxy
public class OperatorAspect {
    @Resource
    private SysLogMapper sysLogMapper;
    @Resource
    private SysLogService sysLogService;

    @Pointcut("@annotation(com.xhlj.annotation.SystemLog)")
    public void logPointcut() {
    }


    @Around("logPointcut()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        /*执行前的日志*/

        Object result = null;
        String remoteAddr = "";
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (sra != null) {
            HttpServletRequest request = sra.getRequest();
            if (request != null) {
                /*到时候尝试一下百度地图*/
                remoteAddr = request.getRemoteAddr();

            }
        }
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        // 获取方法对象
        Method method = methodSignature.getMethod();
        // 获取方法名
        String methodName = method.getName();
        // 获取方法上面的注解
        SystemLog anno = method.getAnnotation(SystemLog.class);
        // 传入方法的参数
        String parameters = method.getParameters().toString();
        SysLog systemLog = new SysLog();
        systemLog.setOperateType(anno.title());
        systemLog.setOperateDesc(anno.content());
        systemLog.setLogTime(new Date());
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        systemLog.setOperator(username);
        systemLog.setOperateAddress(remoteAddr);

        sysLogService.save(systemLog);
        result = joinPoint.proceed();
      /*  if(result instanceof Result){
            Integer code=((Result<?>) result).getCode() ;
            if(code==200)   //设置一下状态
                systemLog.settype
        sysLogService.save(systemLog);

        }*/
        /*方法执行后的的日志*/
        return result;
    }

}
